package com.jojo.intermediate.day10_linkedList;

import com.jojo.elementary.entity.ListNode;

/**
 * 2、两数相加
 *
 * 给你两个非空 的链表，表示两个非负的整数。它们每位数字都是按照逆序的方式存储的，并且每个节点只能存储一位数字。
 * 请你将两个数相加，并以相同形式返回一个表示和的链表。
 * 你可以假设除了数字 0 之外，这两个数都不会以 0开头。
 *
 * 示例 1：
 * 输入：l1 = [2,4,3], l2 = [5,6,4]
 * 输出：[7,0,8]
 * 解释：342 + 465 = 807.
 *
 * 示例 2：
 * 输入：l1 = [0], l2 = [0]
 * 输出：[0]
 *
 * 示例 3：
 * 输入：l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
 * 输出：[8,9,9,9,0,0,0,1]
 */
public class AddTwoNum {

    /**  myCode 转出整型相加 */
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        StringBuilder s1 = new StringBuilder();
        StringBuilder s2 = new StringBuilder();
        while (l1 != null){
            s1.append(l1.val);
            l1 = l1.next;
        }
        while (l2 != null){
            s2.append(l2.val);
            l2 = l2.next;
        }
        int i1 = Integer.parseInt(s1.reverse().toString());
        int i2 = Integer.parseInt(s2.reverse().toString());
        int i = i1 + i2;
        StringBuilder s = new StringBuilder();
        s.append(i);
        s.reverse();
        ListNode node = new ListNode(Integer.parseInt(s.substring(0,1)));
        ListNode cur = node;
        for (int j = 1;j < s.length();j++){
            ListNode newNode = new ListNode(Integer.parseInt(s.substring(j,j + 1)));
            cur.next = newNode;
            cur = newNode;
        }
        return node;
    }

    /**  myCode 模拟 */
    public ListNode addTwoNumbers2(ListNode l1, ListNode l2) {
        ListNode head = null, tail = null;
        int carry = 0;
        while (l1 != null || l2 != null) {
            int n1 = l1 != null ? l1.val : 0;
            int n2 = l2 != null ? l2.val : 0;
            int sum = n1 + n2 + carry;
            if (head == null) {
                head = tail = new ListNode(sum % 10);
            } else {
                tail.next = new ListNode(sum % 10);
                tail = tail.next;
            }
            carry = sum / 10;
            if (l1 != null) {
                l1 = l1.next;
            }
            if (l2 != null) {
                l2 = l2.next;
            }
        }
        if (carry > 0) {
            tail.next = new ListNode(carry);
        }
        return head;
    }

    public static void main(String[] args) {
        ListNode l1 = new ListNode(2);
        ListNode l2 = new ListNode(4);
        ListNode l3 = new ListNode(3);
        l1.next = l2;
        l2.next = l3;
        ListNode l4 = new ListNode(5);
        ListNode l5 = new ListNode(6);
        ListNode l6 = new ListNode(4);
        l4.next = l5;
        l5.next = l6;
        AddTwoNum addTwoNum = new AddTwoNum();
        ListNode listNode = addTwoNum.addTwoNumbers(l1, l4);
        System.out.println(listNode.val + "" + listNode.next.val + "" + listNode.next.next.val);
    }
}
